import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import {get_listexam,get_examType,get_examsubject,get_questions,add_listexam} from '@/services/examList'
import {setCookies} from '@/utils/cook'
import {IExam} from '@/interface/examList'
export interface ExamModelState {
  listexam:IExam[];
  examType:any;
  examsubject:any;
  addlist:any;
}

export interface ExamModelType {
  namespace: 'exam';
  state: ExamModelState;
  effects: {
    getListexam: Effect;
    getExamtype:Effect;
    getExamsubject:Effect;
    getExamquestions:Effect;
    addExamlist:Effect;
  };
  reducers: {
    save: Reducer<ExamModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<ExamModelState>;
  };
  subscriptions: { setup: Subscription };
}

const ExamModel: ExamModelType = {
  namespace: 'exam',

  state: {
    listexam:[],
    examType:[],
    examsubject:[],
    addlist:[]
  },

  effects: {
      //获取试卷列表
    *getListexam({ payload }, { call, put }) {
        let result=yield call(get_listexam);
        //console.log(result);
        if(result.code===1){
            yield put({
                type:'save',
                payload:{listexam:result.exam}
            })
        }
    },
    //获取所有考试的类型
    *getExamtype({payload},{call,put}){
        let result=yield call(get_examType,payload);
        // console.log(result);
        if(result.code===1){
            yield put({
                type:'save',
                payload:{examType:result.data}
            })
        }
    },
    //获取所有的课程
    *getExamsubject({payload},{call,put}){
        let result=yield call(get_examsubject,payload);
        //console.log(result);
        if(result.code===1){
            yield put({
                type:'save',
                payload:{examsubject:result.data}
            })
        }
    },
    //按条件获取试题
    *getExamquestions({payload},{call,put}){
      let result=yield call(get_questions,payload);
      //console.log(result);
      if(result.code===1){
        yield put({
          type:'save',
          payload:{listexam:result.data.filter((item:any)=>item.exam_id===payload.exam_id&&item.subject_id===payload.subject_id)}
        })
      }
    },
    //创建试卷列表
    *addExamlist({payload},{call,put}){
      let result=yield call(add_listexam,payload);
      console.log(result);
      if(result.code===1){
        console.log(result)
        yield put({
          type:'getListexam',
          
        })
      }
    }
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          })
        }
      });
    }
  }
};

export default ExamModel;